import { loginAPI } from '@/api/login.js'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { getUserInfoAPI } from '@/api/user'
const state = () => {
  return {
    token: getToken() || '',
    userInfo: {}
  }
}

const mutations = {
  setToken (state, tokenStr) {
    state.token = tokenStr
    setToken(tokenStr)
  },
  removeToken (state) {
    state.token = ''
    removeToken()
  },
  setUserInfo (state, userInfo) {
    state.userInfo = userInfo
  },
  removeUserInfo (state) {
    state.userInfo = {}
  }
}

const actions = {
  // 登录处理
  async loginAction ({ commit }, data) {
    const res = await loginAPI(data)
    console.log(res)
    commit('setToken', res.token)
  },
  // 获取用户信息
  async getUserInfoAction ({ commit }) {
    try {
      const res = await getUserInfoAPI()
      // console.log('res', res)
      // 存入到vuex中
      commit('setUserInfo', res)
    } catch (e) {
      //
      console.log(e)
    }
  },
  logout ({ commit }) {
    commit('removeToken')
    commit('removeUserInfo')
  }
}
export default {
  // 开启命名空间
  namespaced: true,
  state,
  mutations,
  actions
}
